/**
 * data: {}， // 父节点
 * instanceName: "二级" // 当前点击值
 * params: {
 *     data: {}, // 当前节点数据
 *     // 当前点击按钮
 *     operation: {name: '详情', type: '详情', ico: '28cd926a6065de1b7.png'}
 * }
 * type: "operation" // 操作类型
 */
const { type, params, instanceName, data } = $event;
const helper = new Helper(this);
const gis = helper.get('三维组件');
const queryManage = helper.get('queryManage')?.widgetObj;
const prefix = helper.getVariable("environmentType");
// 应急服务
const emergencyRequest = EmergencyServices.getInstance(prefix);
// const process = this.pageObj.getVariables().find(v => v.name === 'whetherProcess')?.value || 0;


console.log('$event: => ', $event, 'screen_params: => ', data);
helper.setVariable('screen_params', data);

const queryDrillDetail = () => {
    return queryManage.queryDrillDetail(params.data.id).then(res => {
        const { xCoordinate, yCoordinate, zCoordinate, startTime, endTime } = res;
        return {
            ...res,
            drillDatetimeRange: `${startTime} 至 ${endTime}`,
            occurrencePlace: `${xCoordinate} , ${yCoordinate} , ${zCoordinate}`,
        };
    });
};

try {

    const showDrillDetail = () => {
        const $formDetail = helper.get('judge-content');
        const $img = helper.get('detail-img');
        const btns = helper.get('modal-btns')?.widgetObj;
        const { eventDetails } = params.data || {};

        return queryDrillDetail().then(formData => {
            const { xCoordinate, yCoordinate, zCoordinate } = formData;
            gis.widgetObj.setIconPosition({ right: 420, top: 100 });

            // 关闭所有编辑组件
            // this.getApiPage().getApiWidgetsByClassName('edit')?.forEach(v => v.hideWidget());
            helper.hideByCls('edit');
            // 显示所有的 详情组件。
            helper.showByCls('detail');

            formData.pointId = `${xCoordinate},${yCoordinate},${zCoordinate}`
            formData.eventPoint = `${xCoordinate},${yCoordinate},${zCoordinate}`
            $formDetail.widgetObj._option.dataSource = formData;
            $formDetail.widgetObj._option.isDetail = true;
            $formDetail.widgetObj.render();

            // if (+process !== 1) {
            // 不是已结束，就都显示按钮组
            // this.getApiPage().getApiWidgetByAliasName('detail-toggle')?.showWidget()
            // }

            var personCountVar = $($formDetail.__box).find("#d-personCount");

            if (personCountVar && personCountVar[0]) {
                personCountVar[0].innerText = "当前参演人员" + (formData.personCount) + "位";
            }

            var drillStateVar = $($formDetail.__box).find("#d-drillState");

            if (drillStateVar && drillStateVar[0]) {
                drillStateVar[0].innerText = formData.drillState;
            }

            // 编辑状态
            $formDetail.widgetObj.resetForm('form_19');
            $formDetail.widgetObj.setFormData('form_19', formData);
            // 详情状态
            // $formDetail.widgetObj.resetForm('form_20');

            if (+formData.disableFlag === 2 || +formData.disableFlag === 4) {
                btns?.renderJoinDrill();
            } else {
                if (+formData.disableFlag !== 1 && +formData.disableFlag !== 3) btns?.renderDrill();
            }
            if (+formData.disableFlag !== 1 && +formData.disableFlag !== 3) btns?.show();

            if (eventDetails) {
                let info;
                try {
                    info = JSON.parse(eventDetails)
                } catch (e) {
                    console.error(e)
                }
                console.log('info', [{ data: [{ src: info?.thumbnailPath }] }]);

                if (info?.thumbnailPath) {
                    const srcArr = info.thumbnailPath.split(',').map(v => ({ src: v }));
                    $img.widgetObj.setData([{ data: srcArr }]);
                    $img.widgetObj.render();
                } else {
                    $img.widgetObj.setData([{ data: [] }]);
                    $img.widgetObj.render();
                }
            }

            return formData
        });
    };

    function createAssessmentTemp(detail, { assessmentRecords, comprehensiveEvaluation }) {
        const records = assessmentRecords.map(({ quota, score, content }) => (`
      <dd class="layui-row">
        <div class="layui-col-xs5">${quota}：${score}分</div>
        <div class="layui-col-xs7">内容：${content || ''}</div>
      </dd>
    `));

        return (`
      <dl class="vt-rate">
        <dl class="assessment-content">
          <dt class="assessment-title">演练信息：</dt>
          <dd>所属区域：${detail.eventRange          || ''}</dd>
          <dd>演练时间：${detail.drillDatetimeRange  || ''}</dd>
          <dd>演练来源：${detail.source              || ''}</dd>
          <dd>演练名称：${detail.drillName           || ''}</dd>
          <dd>演练类型：${detail.eventType           || ''}</dd>
          <dd>演练等级：${detail.eventGrade          || ''}</dd>
          <dd>演练位置：${detail.drillLocation       || ''}</dd>
          <dd>演练性质：${detail.eventQuality        || ''}</dd>
          <dd>演练范围：${detail.eventRange          || ''}</dd>
          <dd>演练目的：${detail.drillSake           || ''}</dd>
          <dd>演练状态：${detail.disableFlag         || ''}</dd>
          <dd>演练人员：${detail.personCount         || ''}人</dd>
          <dd>演练内容：${detail.drillContent        || ''}</dd>
        </dl>
        <dl class="assessment-content">
          <dt class="assessment-title">
            <span>演练评估：</span>
            <div class="assessment-sale">综合评分：${comprehensiveEvaluation}分</div>
          </dt>
          ${ records.join('') }
        </dl>
      </dl>
      <style>
        .assessment-content {
          margin: 10px;
        }
        .assessment-content .assessment-title {
          position: relative;
          font-size: 18px;
          font-weight: bold;
          color: #63e7f4;
        }
        .assessment-content .assessment-title .assessment-sale {
          position: absolute;
          font-size: 26px;
          right: 10px;
          top: 0;
        }
      </style>
    `)
    }

    function showAssessment(cb) {
        emergencyRequest.getEventRecordByEventId(params?.data?.id).then((result) => {
            if (result.assessmentRecords?.length) {
                queryDrillDetail().then(detail => {
                    console.log(detail);
                    const temp = createAssessmentTemp(detail, result);
                    cb && cb(temp, true);
                });
            } else {
                cb && cb(`<div class="vt-empty">未填写演练评估</div>`);
            }
        });
    }
    // 获取当前演练人员列表
    const requestPerson = (eventId) => (
        emergencyRequest.getRecordFilterCriteriaByEventId(eventId).then((result) => {
            console.log(this, result);
            if (Array.isArray(result?.personList)) return result.personList.map(item => ({
                name: item, value: item,
            }))
        })
    )

    /**
     * 打开演练记录
     */
    const openRecord = () => {
        const { id, disableFlag } = params.data;
        const timeline = helper.show('timelineVertical');
        const formRecord = helper.show('formRecord');
        // const baseForm = this.getApiPage().retrievePlugin('base-forms');

        // 隐藏总结
        helper.hide('summary');
        // timeline.showWidget();
        showDrillDetail();

        // 重置演练记录搜索条件
        formRecord.widgetObj.resetForm(formRecord.widgetObj._option.instanceName);
        // baseForm.resetForm(formRecord.widgetObj._option.instanceName);
        // 成员
        requestPerson(id).then((result) => {
            if (result) {
                formRecord.widgetObj.asyncSelectOptions('personName', result);
            }
        })

        if (timeline && timeline.widgetObj) {
            timeline.widgetObj?.setUpdateStatus?.(disableFlag !== 1);
            // if (setVariable) setVariable('timeline_event_id', data.id);
            // if (setVariable) setVariable('eventId', data.id);
            emergencyRequest.getProcessRecordByEventId(id).then((result) => {
                if (Array.isArray(result)) {
                    timeline.widgetObj.dataSource = result;
                    timeline.widgetObj.render();
                }
                console.log('演练记录： =》 ', result)
            })
        } else {
            layer?.msg('打开演练记录失败！');
        }
    }

    /**
     * 显示演练人员详情
     *
     * @param memberData
     */
    function showDrillMemberDetail (memberData) {
        const memberWidgetObj = helper.get('新增演练人员')?.widgetObj;
        if (memberWidgetObj) {
            memberWidgetObj.showDetail(memberData);
        }
    }

    if (type === 'page') {
        /**
         * 切换分页
         */
        const type = helper.getVariable('panelType') || 0;
        const disableFlag = helper.getVariable('whetherProcess') || 0;
        const searchText = helper.getVariable('event_search') || ''
        const options = {
            pageNum: params,
            pageSize: 10,
            eventTitle: searchText,
            projectCode: JSON.stringify([data.projectCode]),
            disableFlag
        };

        if (+type === 1) {
            options.drillLocation = instanceName
        } else if (+type === 2) {
            options.eventType = instanceName
        } else if (+type === 3) {
            options.eventGrade = instanceName
        } else {
            options.occurrencePlace = instanceName
        }

        console.log($event, data);
        const { panel_config  = {} } = this.widgetObj._option;
        queryManage.queryDrillList(options).then(({ success, result, count, pageNum, ...other }) => {
            console.log({ success, result, count, other })
            if (success) {
                const { page = {} } = panel_config;
                const option = {
                    dataSource: result,
                    total: count,
                    page: { ...page, current: pageNum }
                };
                this.widgetObj.tree.pannelRerender(data.uniqueKey, option)
            }
            // panel.setData([{data: res}]);
            // panel.render()
        })
    } else if (type === 'operation') {
        const { operation, data } = params;
        /**
         * 按钮事件
         */
        switch (operation.type) {
            case '再现': {
                // 隐藏人员明细
                helper.hide('新增演练人员');
                openRecord()
                break;
            }
            case '评估':
                const assessWidget = helper.get('演练评估');
                const assessObj = assessWidget?.widgetObj;
                // 隐藏人员明细
                helper.hide('新增演练人员');
                showAssessment((temp, isDetail) => {
                    $(assessWidget.__box).removeAttr('data-status');
                    assessObj._option.defaultData = data;
                    assessObj?.renderFooter(isDetail && []);
                    assessObj?.renderContent(temp);
                    assessObj?.show();
                });
                break;
            case '总结': {
                // 显示总结
                helper.get('summary').widgetObj.show();

                // 隐藏再现
                // this.getApiPage().getApiWidgetByAliasName('').hideWidget();
                helper.hide('timelineVertical');
                helper.hide('formRecord');
                // 隐藏人员明细
                helper.hide('新增演练人员');

                // 拉取最新数据
                // this.pageObj.setVariables([{ name: 'timeline_event_id', value: data.id }]);
                helper.setVariable('timeline_event_id', data.id);
                // queryDrillDetail().then(detail => {
                //   console.log(detail);
                //   summary.option_dataSource.eventRecord.personCount = detail.personCount;
                //   // summary.eventInfoRender(summary.$detail);
                //   summary.render();
                //   summary.show();
                //   $('#summary .file-box').text(summary.fileName);
                // });
                // window.parent.postMessage({ type: 'nav/style', pageName: '总结' }, document.referrer);
                break;
            }
            case '人员':
            case '明细': {
                // 隐藏总结
                helper.hide('summary');
                // 隐藏再现
                helper.hide('timelineVertical');
                helper.hide('formRecord');
                showDrillDetail().then(res => {
                    showDrillMemberDetail (res)
                });
                break;
            }
            case '详情': {
                showDrillDetail();
                break;
            }
            case '合并列表': {
                // this.pageObj.getApiWidgetsByClassName('event-merge').forEach(v => v.hideWidget());
                helper.hideByCls('event-merge');
                // this.pageObj.getApiWidgetsByClassName().forEach(v => v.showWidget());
                helper.showByCls('event-time');

                // this.pageObj.setVariables([{ name: 'event_parentId', value: data.id }])
                helper.setVariable('event_parentId', data.id);
                break;
            }
            case '合并': {
                // this.pageObj.getApiWidgetsByClassName('event-merge').forEach(v => v.showWidget());
                helper.showByCls('event-merge');
                // this.pageObj.getApiWidgetsByClassName('event-time').forEach(v => v.hideWidget());
                helper.hideByCls('event-time');
                break;
            }
        }
    }
}catch (e) {
    console.error(e)
}
